#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import json
import time
import httplib
import urllib

from subprocess import Popen, PIPE
from Ump import utils 
from Ump.common import log


LOG = log.get_log('Ump.objs.common.httpClient')


def http_exec(proxy_host, host, url, port=27903, timeout=30):
    proxy_host = '127.0.0.1'
    h2 = httplib.HTTPConnection(proxy_host, port, timeout=timeout)
    url = '/%s?%s' %(url, host)
    url = urllib.quote(url)
    h2.putrequest("GET", url)
    #h2.putheader('Content-Type', 'multipart/form-data')
    h2.putheader('Content-Type', 'application/json')
    h2.putheader('Transfer-Encoding', 'chunked')
    h2.endheaders()
    r2 = h2.getresponse()
    content = r2.read()
    content = json.loads(content)
    stdout = content['stdout']
    stderr = content['stderr']
    if stdout == None:
        stdout = ''
    if stdout.find('No license found.') != -1:
        raise LichLiscenFault('No license found.')
    elif stdout.find('Invalid license.') != -1:
        raise LichLiscenFault('Invalid license.')
    elif stdout.find('License expired.') != -1:
        raise LichLiscenFault('License expired.')
    elif stdout.find('Excess capacity.') != -1:
        raise LichLiscenFault('Excess capacity.')
    if not stderr == '':
        if stderr.find('Errno') != -1:
            index = stderr.find('Errno')
            error = stderr[index+10:].strip('>')
            raise Exception('%s'%error)
        errors = stderr.split('\n')
        errors = [error for error in errors if error.startswith('utils.Exp')]
        error = ''.join(errors)
        if errors == []:
            error = stderr
        raise Exception('%s'%error)
    return stdout

def http_down(proxy_host,port,host,timeout=30):
    proxy_host = '127.0.0.1'
    url = '/io.tar.gz'
    url = url + '?%s'%host
    dir_ = '%s/tmp/ump/host/%s' % (utils.install_path, host)
    mkdir_(dir_)
    h2 = httplib.HTTPConnection(proxy_host,port,timeout=timeout)
    url = urllib.quote(url)
    h2.putrequest("GET",url)
    h2.putheader('Content-Type', 'multipart/form-data')
    h2.putheader('Transfer-Encoding', 'chunked')
    h2.endheaders()
    r2 = h2.getresponse()

    content = r2.read()
    fileobj = '%s/%s.tar.gz'%(dir_,time.time())
    fout = open(fileobj,'w')
    fout.write(content)
    fout.close()
    return fileobj

def mkdir_(dir_):
    if not os.path.exists(dir_):
        p1 = Popen(['mkdir','-p',dir_], stdout=PIPE)
        stdout, stderr = p1.communicate()
        if not p1.returncode == 0:
            print >>sys.stderr, 'Warn: create file error', stderr


if __name__ == '__main__':
    host = '192.168.1.140'
    port = '27903'
    url = '/lich.cluster --list?192.168.1.13'
    url = "%s/lich/admin/syncump.py _exec_remote %s --cmd 'hostname'"%'192.168.1.141'
    url = '%s/lich/admin/syncump.py _exec_remote --hostname %s --cmd "cat /etc/hosts"'%'192.168.1.141'
    LOG.info(url)
    s=http_exec(host,'192.168.1.141',url)
    LOG.info(s)
